package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.service.FilerChainService;
import com.qf.service.FilterChainManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * projectName: sms-platform02
 *
 * @author: 元
 * time: 2021/10/18 0018 17:31
 * description:责任管理者实现类
 */
@Slf4j
@Service
public class FilterChainManagerImpl implements FilterChainManager {


    @Autowired
    private CacheFeign cacheFeign;

    @Autowired
    private Map<String, FilerChainService>  filerChainMap;

    @Override
    public void execute(StandardSubmit standardSubmit) {

        //1.获取短信客户端ID
        Integer clientID = standardSubmit.getClientID();

        //2.调用远程Feign接口,根据客户端ID获取客户对象数
        Map clientMap = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + clientID);
        if (clientMap == null){
            log.info("[策略管理者~客户端ID错误]" + clientID);
            return;
        }
        //3.获取缓存中客户设置的过过滤策略名称和执行顺序字符串
        Object strategyObj = clientMap.get("filters");
        if (strategyObj == null){
            log.info("[策略管理者~该客户端没有策略可执行]",+ clientID);
            return;
        }
            //从redis中获取到客户提前设置号的策略和执行顺序
        String [] strategyArray  =String.valueOf(strategyObj).split(",");

        //4.遍历客户设置的策略数组,保证顺序执行
        if (strategyArray != null){
            for (String strategyName : strategyArray){
                //5.根据客户设置的需要执行的策略名称和顺序,匹配具体的策略实现类
                FilerChainService filerChainService = filerChainMap.get(strategyName);
                //执行策略
                boolean flag = filerChainService.strategy(standardSubmit);
                //如果执行失败,则不继续向后执行其他策略
                if (!flag){
                    log.info("[策略管理者~策略链执行失败],客户端id={},clientID={},策略名称={}" + clientID ,strategyName);
                    return;
                }
                log.info("[策略管理者~策略链执行成功],客户端id={},clientID={},策略名称={}" + clientID ,strategyName);
            }
        }

        //通过缓存你模块,存入发送成功的短信的数据和时间戳,做限流
        String sendTimes = String.valueOf(new Date().getTime());
        boolean boo = cacheFeign.zsadd(CacheConstants.CACHE_PREFIX_SMS_LIMIT + standardSubmit.getClientID()
                + ":"+standardSubmit.getDestMobile(),sendTimes,new Date().getTime());





    }
}
